# -*- coding:utf-8 -*-

from ui_export_m import Ui_MainWindow
from PyQt5.QtWidgets import QWidget, QApplication, QFileDialog, QRadioButton, QCheckBox, QMainWindow
from PyQt5.QtCore import pyqtSlot
import sys
import os
import traceback
import VBAPItoPython as vb
import xlsxwriter as xl
from PIL import Image
import openpyxl as xlo


class Mywin(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(Mywin, self).__init__(parent)
        self.setupUi(self)
        self.le_workdir.setText('E:/python/test_data-2/')
        self.le_outdir.setText('E:/python/test_data-3/')
        self.read_list()

    @pyqtSlot()
    def on_pb_choose_outdir_clicked(self):
        outdir = self.opendir()
        self.le_outdir.setText(outdir)


    @pyqtSlot()
    def on_pb_choose_workdir_clicked(self):
        workdir = self.opendir()
        self.le_workdir.setText(workdir)
        self.read_list()


    @pyqtSlot()
    def on_add_model_clicked(self):
        list = self.list_model.selectedItems()
        for item in list:
            self.list_outmodel.addItem(item.text())
            item_row = self.list_model.row(item)
            self.list_model.takeItem(item_row)

    @pyqtSlot()
    def on_pb_export_clicked(self):
        outtype = ''
        for each in self.gb_outtype.findChildren(QRadioButton):
            if each.isChecked():
                outtype = each.text()

        if outtype == 'stp':
            self.export_stp()
    @pyqtSlot()
    def on_pb_read_template_clicked(self):
        self.read_listfromfile()

    def opendir(self):
        dir = QFileDialog.getExistingDirectory()
        return dir+'/'

    def read_list(self):
        workdir = self.le_workdir.text()

        typelist = []
        # 遍历GroupBox中所有RadioButton
        for each in self.gb_intype.findChildren(QCheckBox):
            if each.isChecked():
                typelist.append(each.text())
        os.chdir(workdir)
        # 遍历工作目录指定类型文件
        self.list_model.clear()
        tmp_list = []
        for file in os.listdir():
            if file.split('.')[-2] in typelist:
                filename = file.split('.')[:-1]
                data = '.'.join(filename)
                if data not in tmp_list:
                    tmp_list.append(data)
                tmp_list.sort()
        self.list_model.addItems(tmp_list)

    def read_listfromfile(self):
        outdir = self.le_outdir.text()
        (filename, filetype) = QFileDialog.getOpenFileName(self, '选择文件', outdir, 'excel文件(*.xls, *.xlsx)')
        if filename != '':
            self.list_model.clear()
            wb = xlo.open(filename)
            for sheet in wb:
                list = sheet['B:B']
                for cell in list[1:]:
                    self.list_model.addItem(cell.value + '.prt')

                break

    def export_stp(self):
        outdir = self.le_outdir.text()
        im_width = 60
        im_height = 60
        # 更改工作目录
        os.chdir(outdir)
        # 新建文件
        workbook = xl.Workbook('export_stp.xlsx')
        # 添加工作表
        worksheet = workbook.add_worksheet()
        # 设置单元格格式
        cell_format = workbook.add_format()
        cell_format.set_align('center')
        cell_format.set_align('vcenter')

        # 添加表头
        header = ('No.', '品名/料号', '文件名', '图片', '材质', '外形尺寸')
        worksheet.write_row('A1', header, cell_format)
        # 设置列宽
        worksheet.set_column_pixels(3, 3, im_width)
        worksheet.set_column(1, 2, 23)
        worksheet.set_column(5, 5, 23)
        # 连接现有Creo程序
        connect = vb.IAsyncConnection()
        connect.start(CmdLine='C:/Program Files/PTC/Creo 6.0.4.0/Parametric/bin/parametric.exe')
        # 数据行计数
        index = 1
        try:
            # 创建会话对象并更改工作目录
            session = vb.Isession(connect.session)
            session.set_directory(Path=self.le_workdir.text())
            # 设置背景为白色 快捷键：wb
            session.runmacro(vb.macro.white_background.value)
            # 遍历会话中所有模型
            for i in range(self.list_model.count()):
                # 创建模型实例 使用IpfcModel实例化Imodel
                filename = self.list_model.item(i).text()
                model = vb.Imodel(session.retrieve_model(filename=filename))
                if model.extension == 'prt':
                    model.export(filename=outdir + model.instancname + 'stp')  # 输出stp文件
                    model.display()  # 显示模型
                    window = vb.Iwindow(session.create_modelwindow(model.model))  # 创建窗口实例
                    window.activate()  # 激活窗口
                    # 去除模型颜色并居中
                    session.runmacro(vb.macro.clear_appearance.value)
                    session.runmacro(vb.macro.view_refit.value)
                    # 输出模型截图
                    window.export_jpeg(outdir + model.instancname + '.jpeg')
                    # 输出模型外形尺寸
                    o = model.get_outline()
                    o.sort(reverse=True)
                    outline = ''
                    for i in o:
                        outline += '{:.3f}'.format(i)
                        outline += '*'
                    outline = outline[:-1]
                    # 生成数据行并插入worksheet
                    data = (index, model.instancname, model.instancname, None, model.material, outline)
                    worksheet.write_row(index, 0, data, cell_format)
                    # 格式化图片并插入表格
                    im = Image.open(model.instancname + '.jpeg')
                    x_scale = (im_width - 10) / im.size[0]
                    y_scale = (im_height - 10) / im.size[1]
                    options = {'x_scale': x_scale,
                               'y_scale': y_scale,
                               'x_offset': 5,
                               'y_offset': 5}
                    worksheet.insert_image(index, 3, model.instancname + '.jpeg', options)
                    # 设置行高
                    worksheet.set_row_pixels(index, im_height)
                    # 数据行计数+1
                    index += 1
                    # 关闭图片 避免后面清理图片时被占用无法清理
                    im.close()
                    window.close()
            # 关闭工作部
            workbook.close()

        except Exception as e:
            print(traceback.print_exc())
        finally:
            connect.end()
            # 清理无用文件
            for file in os.listdir():
                if not file.split('.')[-1] in ['stp', 'xlsx']:
                    try:
                        os.remove(file)
                    except Exception as e:
                        print(traceback.print_exc())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mywin = Mywin()
    mywin.show()
    sys.exit(app.exec_())

